package com.atguigu.flink.state;

import com.atguigu.flink.function.WaterSensorMapFunction;
import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.state.ReducingState;
import org.apache.flink.api.common.state.ReducingStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

/**
 * Created by Smexy on 2023/3/1
 *
 *  计算每种传感器的水位和
 */
public class Demo7_KeyedReduceState
{
    public static void main(String[] args) {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

                env
                   .socketTextStream("hadoop103", 8888)
                   .map(new WaterSensorMapFunction())
                   .keyBy(WaterSensor::getId)
                   .process(new KeyedProcessFunction<String, WaterSensor, String>()
                   {
                       //状态自带聚合功能
                       private ReducingState<Integer> sumVC;

                       @Override
                       public void open(Configuration parameters) throws Exception {
                           sumVC = getRuntimeContext().getReducingState(new ReducingStateDescriptor<>("sumVC", new ReduceFunction<Integer>()
                           {
                               @Override
                               public Integer reduce(Integer value1, Integer value2) throws Exception {
                                   return value1 += value2;
                               }
                           }, Integer.class));
                       }

                       @Override
                       public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {

                           //放入当前传感器的水位值，自动聚合
                           sumVC.add(value.getVc());

                           out.collect(ctx.getCurrentKey() + ":"+sumVC.get());
                       }
                   })
                   .print();

                try {
                            env.execute();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

    }
}
